package com.bytech.comment.biz.service.commentThumb.Impl;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bytech.comment.biz.mapper.comment.CommentMapper;
import com.bytech.common.biz.entity.base.BaseResult;
import com.bytech.common.biz.entity.blogUser.BlogUserAgent;
import com.bytech.common.biz.entity.comment.Comment;
import com.bytech.common.biz.entity.comment.CommentDto;
import com.bytech.common.biz.entity.commentThumb.CommentThumb;
import com.bytech.comment.biz.mapper.commentThumb.CommentThumbMapper;
import com.bytech.comment.biz.service.commentThumb.CommentThumbService;
import com.bytech.common.biz.service.base.BasicServiceImpl;
import com.bytech.common.utils.StringUtils;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author Zhao
 * @Create 2021-09-28
 */
@Service
public class CommentThumbServiceImpl extends BasicServiceImpl<CommentThumbMapper, CommentThumb> implements CommentThumbService {

    @Resource
    private CommentThumbMapper commentThumbMapper;
    @Resource
    private CommentMapper commentMapper;

    @Override
    @Transactional
    public BaseResult<Integer> toggleThumb(Long commentId, String userId) {
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null || StringUtils.isBlank(userId)) {
            return BaseResult.<Integer>error("评论或用户信息不能为空").build();
        }
        LambdaQueryWrapper<CommentThumb> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommentThumb::getCommentId, commentId).eq(CommentThumb::getUserId, userId);
        CommentThumb thumb = commentThumbMapper.selectOne(queryWrapper);
        int c = 0;
        if (thumb == null) {
            CommentThumb newThumb = new CommentThumb();
            newThumb.setCommentId(commentId);
            newThumb.setUserId(userId);
            newThumb.setCreateTime(new Date());
            save(newThumb);
            c++;
        } else {
            remove(queryWrapper);
            c--;
        }
        comment.setThumbCount(comment.getThumbCount() == null ? c : comment.getThumbCount() + c);
        commentMapper.updateById(comment);
        return BaseResult.<Integer>success("操作成功！").data(c).build();
    }
}
